<template>
  <div class="p-6">
    <a-space>
      <a-button @click="handleGetAllData">获取全部数据</a-button>
      <a-button @click="handleAppendData">添加一条数据</a-button>
    </a-space>
  </div>
</template>

<script setup>
  const dbName = 'testDB';
  const version = 1;
  const storeName = 'testStore';
  const indexedDB = window.indexedDB;
  let db;
  const request = indexedDB.open(dbName, version);
  request.onsuccess = e => {
    db = e.target.result;
    console.log('打开数据库成功');
  };
  request.onerror = e => {
    console.log('打开数据库失败');
  };
  // 数据库创建或升级的时候会触发
  request.onupgradeneeded = e => {
    console.log('onupgradeneeded');
    db = e.target.result;
    let objectStore;
    if (!db.objectStoreNames.contains(storeName)) {
      objectStore = db.createObjectStore(storeName, {
        keyPath: 'id', // 创建表
      });
    }
  };

  function addData(db, storeName, data) {
    const request = db
      .transaction([storeName], 'readwrite') // 可读写
      .objectStore(storeName) // 仓库对象
      .add(data);

    request.onsuccess = () => {
      alert('写入成功');
    };

    request.onerror = e => {
      alert('写入失败');
      throw new Error(e.target.error);
    };
  }

  function getAllData(db, storeName) {
    const request = db.transaction([storeName]).objectStore(storeName).getAll();
    request.onerror = e => {
      console.log('事务失败');
    };

    request.onsuccess = e => {
      console.log('查询全部结果：', request.result);
    };
  }

  // 根据id获取数据
  function getDataByKey(db, storeName, key) {
    const transaction = db.transaction([storeName]); // 事务
    const objectStore = transaction.objectStore(storeName);
    const request = objectStore.get(key);

    request.onerror = e => {
      console.log('事务失败');
    };

    request.onsuccess = e => {
      console.log('查询结果：', request.result);
    };
  }

  // 根据id修改数据
  function updateDB(db, storeName, data) {
    const request = db
      .transaction([storeName], 'readwrite') // 事务对象
      .objectStore(storeName) // 仓库对象
      .put(data);

    request.onerror = e => {
      console.log('更新失败');
    };

    request.onsuccess = e => {
      console.log('更新成功');
    };
  }

  function deleteDB(db, storeName, id) {
    const request = db.transaction([storeName], 'readwrite').objectStore(storeName).delete(id);

    request.onerror = e => {
      console.log('删除失败');
    };

    request.onsuccess = e => {
      console.log('删除成功');
    };
  }

  function handleGetAllData() {
    getAllData(db, storeName);
  }

  function handleAppendData() {
    addData(db, storeName, {
      id: new Date().getTime(), // 必须且值唯一
      name: '张三',
      age: 18,
      desc: 'helloWord',
    });
  }
</script>
